/*
 * HoangTN
 * servlet controller for log01020.jsp
 */
package vn.edu.fpt.xml.hrm.controller.timesheet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import vn.edu.fpt.xml.hrm.controller.AbstractController;

/**
 *
 * @author HoangTN
 */
public class NewActivitiesController extends AbstractController {

    private final String homePage = "jsp/log01020.jsp";
    private final String errorPage = "jsp/error.jsp";
    private boolean found;

    @Override
    protected String execute() {

        HttpServletRequest request = this.getRequest();
        HttpServletResponse response = this.getResponse();

        String webPath = getServletContext().getRealPath("/");
        String filePath = webPath + "WEB-INF/activities.xml";

        Document doc = NewActivitiesUtil.createDOMTree(filePath);

        String date = request.getParameter("txtDate");
        String description = request.getParameter("txtDescription");
        String project = request.getParameter("txtProject");
        String duration = request.getParameter("txtDuration");

        String url = errorPage;
        String action = request.getParameter("action");

        if (action.equals("Submit")) {
            found = false;
            addNew(date, description, project, duration, doc);
            if (found) {
                url = homePage;
                NewActivitiesUtil.writeXML(doc, filePath);
            }
        }
        return url;
    }

    public void addNew(String date, String description, String project,
            String duration, Document doc) {
        if (doc == null) {
            return;
        }
        try {
            Element node = doc.createElement("activity");

            Element dateEL = doc.createElement("date");
            dateEL.setTextContent(date);
            node.appendChild(dateEL);

            Element descriptionEL = doc.createElement("description");
            descriptionEL.setTextContent(description);
            node.appendChild(descriptionEL);

            Element projectEL = doc.createElement("project");
            projectEL.setTextContent(project);
            node.appendChild(projectEL);

            Element durationEL = doc.createElement("duration");
            durationEL.setTextContent(duration);
            node.appendChild(durationEL);

            ((Node) doc).getFirstChild().appendChild(node);
            found = true;
        } catch (Exception e) {
            e.getMessage();
        }

    }
}
